package com.project.personnel.controller;


import com.project.personnel.entity.Hr;
import com.project.personnel.service.HrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author diaominyh
 * @since 2022-12-12
 */
@RestController
@RequestMapping("/hr")
public class HrController {
    @Resource
    private HrService hrService;
    @Resource
    private BCryptPasswordEncoder passwordEncoder;

    //查询当前管理员
    @GetMapping("/getHr")
    public Hr getHrById(HttpSession session) {
        Hr hr = (Hr) session.getAttribute("HrOne");
        return hrService.getById(hr.getId());
    }

    //修改信息
    @PutMapping("/updateHr")
    public boolean updateHrById(@RequestBody Hr hr) {
        return hrService.updateById(hr);
    }

    //修改密码
    @PutMapping("/updateHrPwd")
    public Object updatePws(HttpSession session, String oldPwd, String newPwd) {
        Map<String, String> map = new HashMap<>();
        Hr hr = (Hr) session.getAttribute("HrOne");
        if (!passwordEncoder.matches(oldPwd, hr.getPassword())) {
            map.put("state", "原密码输入错误");
            return map;
        }
        String newPwd1 = passwordEncoder.encode(newPwd);
        hrService.updatePwd(newPwd1, hr.getId());
        map.put("state","success");
        return map;
    }
    @PostMapping("/hrAdd")
    //添加用户
    public boolean hrAdd(@RequestBody Hr hr){
        return hrService.save(hr);
    }



    //查询
    @GetMapping("/gethrall")
    public List<Hr> getHr(@RequestParam(defaultValue = "1") String name){
        return hrService.getHrByname(name);
    }
}

